package com.bootlever.framework.core;

import com.alibaba.fastjson.JSON;
import com.bootlever.framework.common.config.ConfigItem;
import com.bootlever.framework.common.system.SystemBefore;
import com.bootlever.framework.common.utils.ResourceUtils;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

@ComponentScan(value = {"com.bootlever.framework", "${bootlever.app.basePackage:}"})
@SpringBootApplication
public class BootleverApplicationStarter {

    private static final Logger logger = LoggerFactory.getLogger(BootleverApplicationStarter.class);

//    public static void main(String[] args) {
//        SpringApplication application = new SpringApplication(new Object[] { BootleverApplicationStarter.class });
//        //logger.info("[启动参数："+ StringUtils.join(args,",")+"]");
//        application.run(args);
//        logger.info("******************************WELCOME TO BOOTLEVER********************************");
//    }
    protected final void run(String[] args) throws Exception{
        before();
        innerBefore();
        Properties properties = initMetaData();
        SpringApplication application = new SpringApplication(new Object[]{BootleverApplicationStarter.class});
        application.setDefaultProperties(properties);
        application.run(args);
        innerAfter();
        after();
        logger.info("******************************WELCOME TO BOOTLEVER********************************");
    }

    /**
     * 启动前
     */
    private void innerBefore() throws Exception {
        systemBefore();
    }

    /**
     * 处理实现了SystemBefore接口的方法
     */
    private void systemBefore() throws Exception {
        Reflections reflections = new Reflections("com.bootlever.framework");
        Set<Class<? extends SystemBefore>> set = reflections.getSubTypesOf(SystemBefore.class);
        if (set != null && !set.isEmpty()){
            for (Class clazz : set) {
                if (clazz.isInterface()){
                    continue;
                }
                Object object = clazz.newInstance();
                Method method = clazz.getDeclaredMethod("execute");
                method.setAccessible(true);
                method.invoke(object);
            }
        }
    }

    /**
     * 启动后
     */
    private void innerAfter(){

    }

    private Properties initMetaData() throws Exception {
        Properties properties = new Properties();
        logger.info("开始初始化默认配置");
        Map<String, Object> cfgMap = ResourceUtils.scanResource("classpath*:/cfg/*.cfg", ConfigItem.class);
        if (cfgMap == null || cfgMap.isEmpty()){
            return properties;
        }
        if (logger.isInfoEnabled()){
            logger.info("cfg配置:{}", JSON.toJSON(cfgMap));
        }
        for (Object object : cfgMap.values()){
            List<ConfigItem> list = (List<ConfigItem>) object;
            if (list != null && list.size() >0){
                for (ConfigItem configItem : list){
                    properties.setProperty(configItem.getKey(), configItem.getValue());
                }
            }
        }
        return properties;
    }


    /**
     * 用户APP在系统启动前做的事
     */
    protected void before(){
        logger.debug("启动BootLever前App做的事情");
    }

    /**
     * 用户APP在系统启动后做的事
     */
    protected void after(){
        logger.debug("启动BootLever后App做的事情");
    }
}
